package com.cc.spring.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.cc.spring.common.CommonResp;
import com.cc.spring.domain.User;
import com.cc.spring.resp.UserInfoResp;
import com.cc.spring.service.UserService;
import com.cc.spring.utils.CopyUtil;
import com.cc.spring.utils.HdfsUtil;
import org.apache.http.HttpResponse;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/import")
public class ImportController {
    private static final Logger LOG = LoggerFactory.getLogger(HdfsUtil.class);
    @Autowired
    private UserService userService;
    @Autowired
    private HdfsUtil hdfsUtil;

//    导入模板下载
//    导入功能
    @PostMapping("/user")
    public CommonResp<List<Map<String, Object>>> importUser(MultipartFile file){
        CommonResp<List<Map<String, Object>>> commonResp  = new CommonResp();
        List<Map<String, Object>> mapList = new ArrayList<>();
        if(file.isEmpty()){
            commonResp.setSuccess(false);
            commonResp.setMessage("文件不能为空");
            return commonResp;
        }
        try {
            List<User> users = EasyExcel.read(file.getInputStream()).head(User.class).sheet().doReadSync();
            //            需要判断这个用户是不是存在,为空就查询所有,数据库中查询出来的数据
            List<UserInfoResp> dbUsers = userService.getAllUser(null);
            List<User> dbUsers2 = CopyUtil.copyList(dbUsers, User.class);
//            需要判断所添加的用户名是否存在，存在不能添加
            int isAbleAdd = 0;
            List<User> tempUsers = new ArrayList<>();
            for (User user : users) {
                boolean contains = dbUsers2.contains(user);
//                如果存在那么就不插入
                if(contains){
                    LOG.info("用户名：【{}】存在，导入失败",user.getUserName());
                    Map<String, Object> message = new HashMap<>();
                    message.put("userName",user.getUserName());
                    message.put("message","已存在");
                    mapList.add(message);
                }else {
//                    否则可以导入,这儿使用批量导入的方式,使用一个变量来进行判断
                    tempUsers.add(user);
                    isAbleAdd++;
                }
            }
//            如果不唯一那么证明又可以导入的数据
            if(isAbleAdd > 0){
//                需要建立这个方法，使用in来进行批量的导入
                int i = userService.batchImportUser(tempUsers);
                commonResp.setMessage("导入成功，共导入的用户为：" + i + "条");
                commonResp.setContent(mapList);

            }else {
                commonResp.setSuccess(false);
                commonResp.setMessage("导入失败");
                commonResp.setContent(mapList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            commonResp.setSuccess(false);
        }

        return commonResp;
    }
//    导出excel模板
    @GetMapping("/template")
    public void getExcelTemplate(HttpServletResponse response){
        try {
            response.setHeader("Content-Disposition","attachment;filename="+new String("用户信息.xlsx".getBytes("UTF-8"),"ISO-8859-1"));
            EasyExcel.write(response.getOutputStream(), User.class).sheet("用户信息表").doWrite(null);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
